<template>
  <div class="users-list-container">
    <el-card>
      <div class="header-actions">
        <h2>用户管理</h2>
        <el-button type="primary" @click="showAddUserDialog">
          <EpPlus /> 添加用户
        </el-button>
      </div>

      <!-- 搜索区域 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名或邮箱"
          prefix-icon="Search"
          class="search-input"
          @keyup.enter="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 用户列表 -->
      <el-table
        :data="currentPageUsers"
        border
        stripe
        :loading="loading"
        class="users-table"
        v-if="!isLoadingFailed"
      >
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="username" label="用户名" width="200">
          <template #default="scope">
            <div class="username-with-avatar">
              <el-avatar 
                :src="scope.row.avatar || ''" 
                :alt="scope.row.username"
                class="user-avatar"
              >
                <span>{{ scope.row.username?.substring(0, 1).toUpperCase() }}</span>
              </el-avatar>
              <span class="username-text">{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="240" />
        <el-table-column prop="phone" label="电话" width="170" />
        <el-table-column
          prop="roleId"
          label="角色"
          width="150"
        >
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.roleId)">
              {{ getRoleName(scope.row.roleId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
              {{ scope.row.isActive ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
              size="small"
              type="warning"
              @click="handleEdit(scope.row)"
              class="btn-margin"
            >
              <EpEdit /> 编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              <EpDelete /> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 无搜索结果提示 -->
      <div v-if="userList.length === 0 && searchQuery">
        <el-empty 
          description="没有找到匹配的用户" 
          :image="ElEmpty.PLACEHOLDER_IMAGE_SIMPLE"
        >
          <el-button @click="resetSearch">清除搜索条件</el-button>
        </el-empty>
      </div>

      <!-- 加载失败提示 -->
      <div v-else-if="isLoadingFailed" class="load-error">
        <el-empty 
          description="数据加载失败，请刷新页面重试" 
          :image="ElEmpty.PLACEHOLDER_IMAGE_SIMPLE"
        >
          <el-button type="primary" @click="initPage()">刷新</el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <Pagination
        v-model:pageIndex="pagination.pageIndex"
        v-model:pageSize="pagination.pageSize"
        :total="pagination.total"
        @page-change="loadData"
        class="pagination"
      />
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEditMode ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username" :disabled="isEditMode">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
          <!-- <div class="format-hint">1-20个字符，仅包含字母、数字和下划线</div> -->
        </el-form-item>
        <el-form-item
          v-if="!isEditMode"
          label="密码"
          prop="password"
          :required="!isEditMode"
        >
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
          />
          <div class="format-hint">密码长度至少8位，包含数字、字母</div>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" type="email" placeholder="请输入邮箱" />
          <div class="format-hint">请输入有效的邮箱地址，例如：example@domain.com</div>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入电话号码" />
          <div class="format-hint">请输入11位有效的手机号码，例如：13800138000</div>
        </el-form-item>
       <el-form-item label="角色" prop="role">
        <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="超级管理员" />
            <el-option label="管理员" value="管理员" />
            <el-option label="普通用户" value="普通用户" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="formData.isActive" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteConfirmVisible"
      title="确认删除"
      width="300px"
    >
      <p>确定要删除用户 <strong>{{ currentDeleteUser?.username }}</strong> 吗？</p>
      <template #footer>
        <el-button @click="deleteConfirmVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElEmpty } from 'element-plus'
import { userAPI } from '@/api/user'
import Pagination from '@/components/common/Pagination.vue'

// 状态管理
const loading = ref(false)
const isLoadingFailed = ref(false)
const searchQuery = ref('')

// 分页配置
const pagination = reactive({
  pageIndex: 1,
  pageSize: 50,
  total: 0
})

// 对话框状态
const userDialogVisible = ref(false)
const deleteConfirmVisible = ref(false)
const isEditMode = ref(false)
const currentDeleteUser = ref(null)

// 表单数据和验证
const formData = reactive({
  // id: '',
  username: '',
  email: '',
  phone: '',
  roleId:  '0e2b159c-e850-4b95-b707-537ce9ecd029',
  password: '',
  // avatar: '',
  isActive: true
})

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '用户名长度在1-20个字符之间', trigger: 'blur' },
    // { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' },
    {pattern:/^[A-Za-z0-9]+$/,message: '密码只能包含字母、数字'}
  ]
}

// 表单引用
const userFormRef = ref(null)

// 用户列表
const userList = ref([])

// 当前页显示的用户数据
const currentPageUsers = computed(() => {
  return userList.value
})

// 角色类型和名称映射
const roleMap = {
  '超级管理员': 'cc5b04a1-89d1-486b-b658-d37ddcc6596d',
  '管理员': '94746ead-9785-4a40-b1d5-eeb2e149d2ca',
  '普通用户': '0e2b159c-e850-4b95-b707-537ce9ecd029'
}

const reverseRoleMap = {
  'cc5b04a1-89d1-486b-b658-d37ddcc6596d': '超级管理员',
  '94746ead-9785-4a40-b1d5-eeb2e149d2ca': '管理员',
  '0e2b159c-e850-4b95-b707-537ce9ecd029': '普通用户'
}

const getRoleName = (roleId) => {
  return reverseRoleMap[roleId] || '未知角色'
}

const getRoleType = (roleId) => {
  if (roleId === 'cc5b04a1-89d1-486b-b658-d37ddcc6596d') return 'danger'    // 超级管理员
  if (roleId === '94746ead-9785-4a40-b1d5-eeb2e149d2ca') return 'warning'   // 管理员
  return 'success'                     // 普通用户
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    isLoadingFailed.value = false
     const response = await userAPI.getUserList({
       pageIndex: pagination.pageIndex,
       pageSize: pagination.pageSize,
     })
     console.log(response);
     
    if (response.code === 200) {
      // userList.value = response.data || []

       userList.value = (response.data || []).sort((a, b) => {
        // 定义角色优先级
        const rolePriority = {
          'cc5b04a1-89d1-486b-b658-d37ddcc6596d': 1, // 超级管理员
          '94746ead-9785-4a40-b1d5-eeb2e149d2ca': 2, // 管理员
          '0e2b159c-e850-4b95-b707-537ce9ecd029': 3  // 普通用户
        }
        
        return rolePriority[a.roleId] - rolePriority[b.roleId]
      })

      // 如果没有返回总数，可以使用数组长度
      pagination.total = response.data.length
    } else {
      throw new Error(response.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    isLoadingFailed.value = true
    ElMessage.error(error.message || '数据加载失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = async() => {
  pagination.pageIndex = 1  
  if(searchQuery.value == ""){
    loadData() 
  }else{
    const response = await userAPI.getUserByName(searchQuery.value)
   if (response.code === 200) {
     // 过滤掉 isDelete 为 true 的数据，然后排序
      userList.value = (response.data || [])
        .filter(user => !user.isDelete)  // 新增过滤条件
        .sort((a, b) => {
          const rolePriority = {
            'cc5b04a1-89d1-486b-b658-d37ddcc6596d': 1, // 超级管理员
            '94746ead-9785-4a40-b1d5-eeb2e149d2ca': 2, // 管理员
            '0e2b159c-e850-4b95-b707-537ce9ecd029': 3  // 普通用户
          }
          return rolePriority[a.roleId] - rolePriority[b.roleId]
        })
    
    // 如果没有返回总数，可以使用数组长度
      pagination.total = response.data.length
    } else {
      throw new Error(response.msg || '获取用户列表失败')
    }
  }
  
  
}

const resetSearch = () => {
  searchQuery.value = ''
  pagination.pageIndex = 1
  loadData()
}

// 初始化页面数据
const initPage = () => {
  loadData()
}

// 编辑用户
const handleEdit = (row) => {
  isEditMode.value = true
  // 深拷贝避免直接修改源数据
  const userData = JSON.parse(JSON.stringify(row))
  formData.id = userData.id
  formData.username = userData.username
  formData.email = userData.email || ''
  formData.phone = userData.phone || ''
  formData.role = reverseRoleMap[userData.roleId] || '普通用户'
  formData.avatar = userData.avatar || ''
  formData.password = ''
  formData.isActive = userData.isActive ?? true
  userDialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
   // 检查是否是超级管理员
  if (row.roleId === 'cc5b04a1-89d1-486b-b658-d37ddcc6596d') {
    ElMessage.warning('超级管理员不能被删除')
    return
  }
  
  currentDeleteUser.value = row
  deleteConfirmVisible.value = true
}

const confirmDelete = async () => {
  if (currentDeleteUser.value) {
    // 再次确认不是超级管理员（双重保险）
    if (currentDeleteUser.value.roleId === 'cc5b04a1-89d1-486b-b658-d37ddcc6596d') {
      ElMessage.warning('超级管理员不能被删除')
      deleteConfirmVisible.value = false
      return
    }
    try {
      loading.value = true
      const response = await userAPI.deleteUser(currentDeleteUser.value.id)
      
      if (response.code === 200) {
        ElMessage.success(`用户 ${currentDeleteUser.value.username} 已删除`)
        // 从列表中移除
        const index = userList.value.findIndex(
          user => user.id === currentDeleteUser.value.id
        )
        if (index !== -1) {
          userList.value.splice(index, 1)
        }
        deleteConfirmVisible.value = false
        currentDeleteUser.value = null
      } else {
        throw new Error(response.msg || '删除用户失败')
      }
    } catch (error) {
      ElMessage.error(error.message || '删除用户失败')
    } finally {
      loading.value = false
    }
  }
}

// 添加用户
const showAddUserDialog = () => {
  isEditMode.value = false
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  formData.id = ''
  formData.role = '普通用户'
  formData.avatar = ''
  formData.isActive = true
  userDialogVisible.value = true
}

// 提交用户表单
const submitUserForm = async () => {
  try {
    await userFormRef.value.validate()
    loading.value = true

     // 转换角色名称为ID
    const roleId = roleMap[formData.role]        
    if (isEditMode.value) {
      const updateData = {
        Username: formData.username,
        Email: formData.email,
        Phone: formData.phone,
        roleId: roleId ,
        // avatar: formData.avatar,
        isActive: formData.isActive,
        password:formData.password,
      }
      // if(roleMap[formData.role] == '超级管理员'){
      //   ElMessage.warning('超级管理员不能编辑')
      // }
      // 调用API更新
      const response = await userAPI.updateUser(formData.id,updateData)
      if(response.data == '用户已被禁用'){
        await userAPI.enableUser(formData.id)
      }
      console.log(response);
      
      if (response.code === 200) {
        ElMessage.success('用户信息更新成功')
        // 更新本地列表
        loadData()
        userDialogVisible.value = false
      } else {
        throw new Error(response.msg || '更新用户失败')
      }
    } else {
      console.log(formData);
      const createData = {
        username: formData.username,
        email: formData.email,
        phone: formData.phone,
        role: roleId,
        // avatar: formData.avatar,
        isActive: formData.isActive,
        ...(formData.password && { password: formData.password })
      }
      
      // 调用API添加
      const response = await userAPI.createUser(createData)
      
      
      if (response.code === 200) {
        ElMessage.success('用户添加成功')
        // 添加到本地列表
        userList.value.push({
          id: response.data.id,
          username: formData.username,
          email: formData.email,
          phone: formData.phone,
          role: roleId  ,
          avatar: formData.avatar || '',
          isActive: formData.isActive
        })
        userDialogVisible.value = false

        console.log(response);
      } else {
        throw new Error(response.msg || '添加用户失败')
      }
    }
  } catch (error) {
    console.error('提交失败:', error)
    if (error.name !== 'ValidationError') {
      ElMessage.error(error.message || '操作失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 页面加载时初始化
onMounted(() => {
  initPage()
})
</script>

<style scoped>
.users-list-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  min-width: 300px;
  flex: 1;
  max-width: 500px;
}

.users-table {
  width: 100%;
  margin-bottom: 20px;
}

.username-with-avatar {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  font-size: 14px;
}

.username-text {
  line-height: 32px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 140px;
}

.pagination-container {
  text-align: right;
  margin-top: 15px;
}

.btn-margin {
  margin-right: 5px;
}

.user-form {
  margin-top: 10px;
}

.format-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  line-height: 1.5;
}

.load-error {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .search-input {
    min-width: 0;
    width: 100%;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>